package ru.yermak.bookkeeping.currency;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Order;
import ru.yermak.bookkeeping.model.Currency;
import ru.yermak.bookkeeping.model.User;
import ru.yermak.bookkeeping.model.Group;

import javax.annotation.Resource;
import java.util.List;

/**
 * User: harrier
 * Date: Sep 9, 2008
 */

@Repository
public class HibernateCurrencyDao implements CurrencyDao{
    private HibernateTemplate hibernateTemplate;

    @Autowired
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    public List<Currency> findCurrencyByUserId(Integer userId) {
        User user = (User) hibernateTemplate.get(User.class, userId);
        Group group = user.getGroup();
        List<Currency> currencies = hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Currency.class)
                .add(Restrictions.eq("group", group)).addOrder(Order.asc("code")));
        hibernateTemplate.initialize(currencies);
        return currencies;
    }

    public Integer insertCurrency(Currency currency) {
        Integer currencyId = (Integer) hibernateTemplate.save(currency);
        return currencyId;

    }

    public void removeCurrency(Currency currency) {
        hibernateTemplate.delete(currency);
    }

    public Currency getById(Integer currencyId) {
        return (Currency) hibernateTemplate.load(Currency.class, currencyId);
    }

    public void updateCurrency(Currency currency) {
        hibernateTemplate.persist(currency);
    }


}
